package com.oa.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oa.server.config.security.JwtTokenUtil;
import com.oa.server.entity.Admin;
import com.oa.server.entity.AdminRole;
import com.oa.server.entity.Menu;
import com.oa.server.entity.Role;
import com.oa.server.mapper.AdminMapper;
import com.oa.server.mapper.AdminRoleMapper;
import com.oa.server.mapper.RoleMapper;
import com.oa.server.result.ResponseBean;
import com.oa.server.service.IAdminService;
import com.oa.server.util.AdminUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mcy
 * @since 2021-06-01
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private AdminRoleMapper adminRoleMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    /**
     * 登录之后返回token
     * @param username
     * @param password
     * @param code
     * @param request
     * @return
     */
    @Override
    public ResponseBean login(String username, String password, String code, HttpServletRequest request) {
        // 从session中获取captcha
        String captcha = (String) request.getSession().getAttribute("captcha");
        if(StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)){
            return ResponseBean.error("验证码输入错误，请重新输入！");
        }
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if(null==userDetails||passwordEncoder.matches(password,userDetails.getPassword())){
            return ResponseBean.error("用户名或密码不正确");
        }
        if(!userDetails.isEnabled()){
            return  ResponseBean.error("账号被禁用，请联系管理员");
        }
        // 更新security 登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHeader",tokenHeader);
        return ResponseBean.success("登录成功",tokenMap);
    }

    /**
     * 根据用户名获取密码
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUsername(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username).eq("enabled",true));
    }

    @Override
    public List<Role> getRolesByAdminId(Integer adminId) {
        return roleMapper.getRolesByAdminId(adminId);
    }

    @Override
    public List<Admin> getAllAdmins(String keyWord) {
       return adminMapper.getAllAdmins(AdminUtils.getCurrentAdmin().getId(),keyWord);
    }

    @Override
    @Transactional
    public ResponseBean updateAdminRole(Integer adminId, Integer[] rids) {
            adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId",adminId));
            Integer result =adminRoleMapper.addAdminRole(adminId,rids);

            if(rids.length==result){
                return ResponseBean.success("更新成功");
            }
            return ResponseBean.error("更新失败");
    }


}
